package impl

import (
	"errors"
	"gorm.io/gorm"
	"mvip-route/config"
	"mvip-route/const"
	"mvip-route/service/model"
	"time"
)

type DamDomainIpService struct{}

func (s *DamDomainIpService) CreateDamDomain(newDamDomain model.DamDomainIpModel) (*model.DamDomainIpModel, error) {
	newDamDomain.State = 0
	newDamDomain.AdminPhone = "13435730481"
	newDamDomain.CreateTime = time.Now()
	if err := config.DB.Table("dam_domain_ip_map").Create(&newDamDomain).Error; err != nil {
		return nil, err
	}
	return &newDamDomain, nil
}
func (s *DamDomainIpService) DeleteDamDomain(id int) error {
	return config.DB.Table("dam_domain_ip_map").Where("id = ? and is_deleted = 0", id).Update("is_deleted", 1).Error
}
func (s *DamDomainIpService) GetDamDomain() ([]model.DamDomainIpModel, error) {
	var damDomain []model.DamDomainIpModel
	if err := config.DB.Table("dam_domain_ip_map").Where("is_deleted = 0").Order("id desc").Find(&damDomain).Error; err != nil {
		return nil, err
	}
	return damDomain, nil
}
func (s *DamDomainIpService) UpdateDamDomain(id int) (string, error) {
	result := config.DB.Table("dam_domain_ip_map").Where("id = ? and is_deleted = 0", id).Updates(map[string]interface{}{"state": 1, "update_time": time.Now()})
	if result.Error != nil {
		return _const.ErrDBFailed, result.Error
	}
	if result.RowsAffected == 0 {
		return _const.ErrNotFound, result.Error
	}
	return _const.SuccessMsg, nil
}
func (s *DamDomainIpService) GetActiveDomainMap() (map[string]string, error) {
	domains, err := s.GetDamDomain() // 复用现有方法
	if err != nil {
		return nil, err
	}
	domainMap := make(map[string]string)
	for _, d := range domains {
		if d.State == 0 { // 有效状态校验
			domainMap[d.Domain] = d.Ip
		}
	}
	return domainMap, nil
}
func (s *DamDomainIpService) GetOriginalRecordID(domain string) (int, error) {
	var record model.DamDomainIpModel
	err := config.DB.Table("dam_domain_ip_map").
		Select("id").
		Where("domain = ? AND state = 0 AND is_deleted = 0", domain).
		First(&record).Error

	if errors.Is(err, gorm.ErrRecordNotFound) {
		return 0, errors.New("未找到有效记录")
	}
	return record.ID, err
}
